using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using IGlobalist.Cms.Common;
using IGlobalist.Cms.Bll;
using IGlobalist.Cms.Model;
using IGlobalist.Cms.Presentation;
using com.paypal.soap.api;
using GCheckout.Checkout;
using GCheckout.Util;
using GCheckout.AutoGen;


namespace IGlobalist.Cms
{
    public partial class ShoppingCart : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string productID = Request["pid"];
                IOrder order = new Order();
                Boolean add = true;

                IOrderLine orderLine = new OrderLine();
                OrderLineList listLine = new OrderLineList();

                if (Session[SessionVariable.ShoppingCart.CurrentShoppingCart] != null)
                {
                    PaymentPro.SetProfilePaypalInfo();
                    order = (IOrder)Session[SessionVariable.ShoppingCart.CurrentShoppingCart];
                    listLine = order.OrderLineList;

                    #region paypal- creditcard
                   
                        if ((Request["save"] != null) && (Request["save"] == "1"))
                        {
                            //saveOrder
                            SaveOrder(order);
                            //payment
                            PayPalAPI api = new PayPalAPI();
                            int expMonth = int.Parse(Request["ddlMoth"]);
                            int expYear = int.Parse(Request["ddlYear"]);
                            PayPalResponse = api.DoDirectPayment(
                                 order.Total.ToString(),
                                 Request["txtNameBill"],
                                 Request["txtLastNameBill"],
                                 Request["txtAddress1Bill"],
                                 Request["txtAddress2Bill"],
                                 Request["txtCityBill"],
                                 Request["state"],
                                 Request["txtZipBill"],
                                 Request["cardtype"],
                                 Request["txtCardNumber"],
                                 Request["txtCardDes"],
                                 expMonth,
                                 expYear, PaymentActionCodeType.Authorization);

                            Session["Url"] = Request.UrlReferrer.PathAndQuery;

                            if (ViewState["payment"] != null)
                            {
                                string url = Request.UrlReferrer.PathAndQuery;
                                url = url.Substring(0, url.IndexOf("?"));
                                url = url + "?sumOrder=1";
                                Session["Url"] = url;
                                ViewState["payment"] = null;
                            }
                            Response.Redirect("Receipt.aspx");
                        }
                    #endregion

                    #region google checkout

                        if ((Request["save"] != null) && (Request["save"] == "2"))
                        {
                            SaveOrder(order);
                            PaymentInfo payment = PaymentPro.GetProfileGogleCheckOut();
                             CheckoutShoppingCartRequest Req;
                             if (payment.GoogleEnvironment == "Production")
                                Req = new CheckoutShoppingCartRequest(payment.GoogleMerchantID, payment.GoogleMerchantKey, GCheckout.EnvironmentType.Production, "USD", 0);
                            else
                                Req = new CheckoutShoppingCartRequest(payment.GoogleMerchantID, payment.GoogleMerchantKey, GCheckout.EnvironmentType.Sandbox, "USD", 0);

                            foreach (OrderLine or in order.OrderLineList)
                            {
                                Req.AddItem(string.Format("{0}", or.Name), or.Description, Convert.ToDecimal(or.Price), 1);
                            }
                            GCheckoutResponse Resp = Req.Send();

                          
                            Response.Redirect(Resp.RedirectUrl, true);

                        }
                    #endregion
                }
                else
                {
                    IList<ICmsClass> orderList = ClassController.GetClassListByClassTypeID(Convert.ToInt16(CmsObjectType.Order));
                    ICmsClass orderClass = (ICmsClass)orderList[0];
                    order.ClassTypeID = Convert.ToInt16(CmsObjectType.Order);
                    order.ClassID = orderClass.ID;
                    order.Class = orderClass;
                    order.ExtPropertyList = orderClass.PropertyList;
                    order.CustomerID = 1;
                }



                #region Add/edit

                if ((Request["pid"] != null) && (Convert.ToInt64(productID) > 0))
                {
                    IProduct product = ProductController.GetProduct(Convert.ToInt64(Request["pid"]));
                    IList<ICmsClass> orderLineList = ClassController.GetClassListByClassTypeID(Convert.ToInt16(CmsObjectType.OrderLine));

                    if (orderLineList.Count > 0)
                    {
                        ICmsClass orderLineClass = (ICmsClass)orderLineList[0];
                        orderLine.ClassTypeID = Convert.ToInt16(CmsObjectType.OrderLine);
                        orderLine.Class = orderLineClass;
                        orderLine.ClassID = orderLineClass.ID;
                        orderLine.ExtPropertyList = orderLineClass.PropertyList;
                        orderLine.CreatedDate = DateTime.Now;
                        orderLine.Price = product.Price;
                        orderLine.SalePrice = product.PriceSale;
                        orderLine.Name = product.Name;
                        orderLine.Description = product.Description;
                        orderLine.Quantity = 1;
                        orderLine.ProductID = product.ID;
                    }

                    if (Convert.ToString(Request["update"]) == "1")
                    {
                        try
                        {
                            //update
                            foreach (OrderLine or in listLine)
                            {
                                if (or.ProductID == Convert.ToInt64(productID))
                                {
                                    if (Request["qty" + productID] == "0")
                                        listLine.Remove(or);
                                    else
                                        or.Quantity = Convert.ToInt32(Request["qty" + productID]);
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        if (Convert.ToString(Request["remove"]) == "1")
                        {
                            foreach (OrderLine or in listLine)
                            {
                                if (or.ProductID == Convert.ToInt64(productID))
                                {
                                    listLine.Remove(or);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            foreach (OrderLine or in listLine)
                            {
                                if (or.ProductID == Convert.ToInt64(productID))
                                {
                                    or.Quantity += 1;
                                    add = false;
                                    break;
                                }
                            }
                            if (add == true)
                                listLine.Add(orderLine);
                        }
                    }

                    order.OrderLineList = listLine;

                    Session[SessionVariable.ShoppingCart.CurrentShoppingCart] = order;

                }
                #endregion

                
                Session["Url"] = Request.UrlReferrer.PathAndQuery;
                //Session["Url"] = Request["page"] + "_0_0/default.aspx?shopping=1";

                Response.Redirect(string.Format("{0}?shopping=1",Convert.ToString(Session["Url"])));

            }
        }

        public override void DataBind()
        {
            if (this.TransactionID != null)
            {
                PayPalAPI api = new PayPalAPI();
                this.PayPalResponse = api.GetTransactionDetails(this.TransactionID);
            }
            base.DataBind();
        }

        public void SaveOrder(IOrder order)
        {
            order.Name = "" + Request["txtNameBill"];
            order.OrderCreated = DateTime.Now;
            order.OrderStatus = OrderStatus.Pending;
            order.ShippingAddress1 = "" + Request["txtAddress1Bill"];
            order.ShippingAddress2 = "" + Request["txtAddress2Bill"];
            order.ShippingCity = "" + Request["txtCityBill"];
            order.ShippingCountry = "" + Request["ddlCountryBill"];
            order.ShippingState = "" + Request["state"];
            order.OrderComments = "" + Request["txtCardDes"];
            OrderController.InsertOrder(order);
            Session[SessionVariable.ShoppingCart.CurrentShoppingCart] = order;
            ViewState["payment"] = 1;


        }
    }
}
